!pip install yfinance
!pip install bs4
!pip install nbformat
!pip install plotly
import yfinance as yf
import pandas as pd
import requests
from bs4 import BeautifulSoup
import plotly.graph_objects as go
from plotly.subplots import make_subplots
Requirement already satisfied: yfinance in c:\users\lenovo\anaconda3\lib\site-packages (0.2.48) Requirement already satisfied: beautifulsoup4>=4.11.1 in c:\users\lenovo\anaconda3\lib\site-packages (from yfinance) (4.12.3) Requirement already satisfied: multitasking>=0.0.7 in c:\users\lenovo\anaconda3\lib\site-packages (from yfinance) (0.0.11) Requirement already satisfied: lxml>=4.9.1 in c:\users\lenovo\anaconda3\lib\site-packages (from yfinance) (5.3.0) Requirement already satisfied: peewee>=3.16.2 in c:\users\lenovo\anaconda3\lib\site-packages (from yfinance) (3.17.7) Requirement already satisfied: requests>=2.31 in c:\users\lenovo\anaconda3\lib\site-packages (from yfinance) (2.32.3) Requirement already satisfied: pytz>=2022.5 in c:\users\lenovo\anaconda3\lib\site-packages (from yfinance) (2024.2) Requirement already satisfied: numpy>=1.16.5 in c:\users\lenovo\anaconda3\lib\site-packages (from yfinance) (1.20.3) Requirement already satisfied: frozendict>=2.3.4 in c:\users\lenovo\anaconda3\lib\site-packages (from yfinance) (2.4.6) Requirement already satisfied: html5lib>=1.1 in c:\users\lenovo\anaconda3\lib\site-packages (from yfinance) (1.1) Requirement already satisfied: pandas>=1.3.0 in c:\users\lenovo\anaconda3\lib\site-packages (from yfinance) (1.3.4) Requirement already satisfied: platformdirs>=2.0.0 in c:\users\lenovo\appdata\roaming\python\python39\site-packages (from yfinance) (2.6.0) Requirement already satisfied: soupsieve>1.2 in c:\users\lenovo\anaconda3\lib\site-packages (from beautifulsoup4>=4.11.1->yfinance) (2.2.1) Requirement already satisfied: webencodings in c:\users\lenovo\anaconda3\lib\site-packages (from html5lib>=1.1->yfinance) (0.5.1) Requirement already satisfied: six>=1.9 in c:\users\lenovo\appdata\roaming\python\python39\site-packages (from html5lib>=1.1->yfinance) (1.16.0) Requirement already satisfied: python-dateutil>=2.7.3 in c:\users\lenovo\appdata\roaming\python\python39\site-packages (from pandas>=1.3.0->yfinance) (2.8.2) Requirement already satisfied: charset-normalizer<4,>=2 in c:\users\lenovo\anaconda3\lib\site-packages (from requests>=2.31->yfinance) (2.0.4) Requirement already satisfied: idna<4,>=2.5 in c:\users\lenovo\anaconda3\lib\site-packages (from requests>=2.31->yfinance) (3.2) Requirement already satisfied: certifi>=2017.4.17 in c:\users\lenovo\anaconda3\lib\site-packages (from requests>=2.31->yfinance) (2021.10.8) Requirement already satisfied: urllib3<3,>=1.21.1 in c:\users\lenovo\anaconda3\lib\site-packages (from requests>=2.31->yfinance) (1.26.7) Requirement already satisfied: bs4 in c:\users\lenovo\anaconda3\lib\site-packages (0.0.1) Requirement already satisfied: beautifulsoup4 in c:\users\lenovo\anaconda3\lib\site-packages (from bs4) (4.12.3) Requirement already satisfied: soupsieve>1.2 in c:\users\lenovo\anaconda3\lib\site-packages (from beautifulsoup4->bs4) (2.2.1) Requirement already satisfied: nbformat in c:\users\lenovo\anaconda3\lib\site-packages (5.1.3) Requirement already satisfied: ipython-genutils in c:\users\lenovo\anaconda3\lib\site-packages (from nbformat) (0.2.0) Requirement already satisfied: jsonschema!=2.5.0,>=2.4 in c:\users\lenovo\anaconda3\lib\site-packages (from nbformat) (3.2.0) Requirement already satisfied: traitlets>=4.1 in c:\users\lenovo\appdata\roaming\python\python39\site-packages (from nbformat) (5.7.1) Requirement already satisfied: jupyter-core in c:\users\lenovo\appdata\roaming\python\python39\site-packages (from nbformat) (5.1.0) Requirement already satisfied: setuptools in c:\users\lenovo\anaconda3\lib\site-packages (from jsonschema!=2.5.0,>=2.4->nbformat) (58.0.4) Requirement already satisfied: pyrsistent>=0.14.0 in c:\users\lenovo\anaconda3\lib\site-packages (from jsonschema!=2.5.0,>=2.4->nbformat) (0.18.0) Requirement already satisfied: six>=1.11.0 in c:\users\lenovo\appdata\roaming\python\python39\site-packages (from jsonschema!=2.5.0,>=2.4->nbformat) (1.16.0) Requirement already satisfied: attrs>=17.4.0 in c:\users\lenovo\anaconda3\lib\site-packages (from jsonschema!=2.5.0,>=2.4->nbformat) (21.2.0) Requirement already satisfied: pywin32>=1.0 in c:\users\lenovo\appdata\roaming\python\python39\site-packages (from jupyter-core->nbformat) (305) Requirement already satisfied: platformdirs>=2.5 in c:\users\lenovo\appdata\roaming\python\python39\site-packages (from jupyter-core->nbformat) (2.6.0) Requirement already satisfied: plotly in c:\users\lenovo\anaconda3\lib\site-packages (5.24.1) Requirement already satisfied: tenacity>=6.2.0 in c:\users\lenovo\anaconda3\lib\site-packages (from plotly) (9.0.0) Requirement already satisfied: packaging in c:\users\lenovo\appdata\roaming\python\python39\site-packages (from plotly) (22.0)
import warnings
# Ignore all warnings
warnings.filterwarnings("ignore", category=FutureWarning)
def make_graph(stock_data, revenue_data, stock):
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, subplot_titles=("Historical Share Price", "Historical Revenue"), vertical_spacing = .3)
stock_data_specific = stock_data[stock_data.Date <= '2021--06-14']
revenue_data_specific = revenue_data[revenue_data.Date <= '2021-04-30']
fig.add_trace(go.Scatter(x=pd.to_datetime(stock_data_specific.Date, infer_datetime_format=True), y=stock_data_specific.Close.astype("float"), name="Share Price"), row=1, col=1)
fig.add_trace(go.Scatter(x=pd.to_datetime(revenue_data_specific.Date, infer_datetime_format=True), y=revenue_data_specific.Revenue.astype("float"), name="Revenue"), row=2, col=1)
fig.update_xaxes(title_text="Date", row=1, col=1)
fig.update_xaxes(title_text="Date", row=2, col=1)
fig.update_yaxes(title_text="Price ($US)", row=1, col=1)
fig.update_yaxes(title_text="Revenue ($US Millions)", row=2, col=1)
fig.update_layout(showlegend=False,
height=900,
title=stock,
xaxis_rangeslider_visible=True)
fig.show()
Using the Ticker function enter the ticker symbol of the stock we want to extract data on to create a ticker object. The stock is Tesla and its ticker symbol is TSLA
import yfinance as yf
tsla = yf.Ticker("TSLA")
Using the ticker object and the function history extract stock information and save it in a dataframe named tesla_data. Set the period parameter to "max" so we get information for the maximum amount of time.
tesla_data = pd.DataFrame(tsla.history(period="max"))
Reset the index using the reset_index(inplace=True) function on the tesla_data DataFrame and display the first five rows of the tesla_data dataframe using the head function. Take a screenshot of the results and code from the beginning of Question 1 to the results below.
tesla_data.reset_index(inplace=True)
tesla_data.head()
| Date | Open | High | Low | Close | Volume | Dividends | Stock Splits | |
|---|---|---|---|---|---|---|---|---|
| 0 | 2010-06-29 00:00:00-04:00 | 1.266667 | 1.666667 | 1.169333 | 1.592667 | 281494500 | 0.0 | 0.0 |
| 1 | 2010-06-30 00:00:00-04:00 | 1.719333 | 2.028000 | 1.553333 | 1.588667 | 257806500 | 0.0 | 0.0 |
| 2 | 2010-07-01 00:00:00-04:00 | 1.666667 | 1.728000 | 1.351333 | 1.464000 | 123282000 | 0.0 | 0.0 |
| 3 | 2010-07-02 00:00:00-04:00 | 1.533333 | 1.540000 | 1.247333 | 1.280000 | 77097000 | 0.0 | 0.0 |
| 4 | 2010-07-06 00:00:00-04:00 | 1.333333 | 1.333333 | 1.055333 | 1.074000 | 103003500 | 0.0 | 0.0 |
Use the requests library to download the webpage https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0220EN-SkillsNetwork/labs/project/revenue.htm Save the text of the response as a variable named html_data.
url = "https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0220EN-SkillsNetwork/labs/project/revenue.htm"
html_data = requests.get(url).text
Parse the html data using beautiful_soup using parser i.e html5lib or html.parser.
beautiful_soup = BeautifulSoup(html_data,'html.parser')
Using BeautifulSoup or the read_html function extract the table with Tesla Revenue and store it into a dataframe named tesla_revenue. The dataframe should have columns Date and Revenue.
# Step 1-2: Create an empty DataFrame
tesla_revenue = pd.DataFrame(columns=["Date", "Revenue"])
# Step 3: Locate the relevant table
# Find all tbody elements and select the second one where the Tesla revenue table is located
table = beautiful_soup.find_all("tbody")[1]
# Step 4: Iterate through rows in the table body
for row in table.find_all("tr"):
columns = row.find_all("td")
# Check if there are two columns (Date and Revenue) in each row
if len(columns) == 2:
date = columns[0].text.strip() # Extract and clean the Date text
revenue = columns[1].text.strip() # Extract and clean the Revenue text
#Step 5: Extract Data from Columns
if revenue:
tesla_revenue = tesla_revenue.append({"Date": date, "Revenue": revenue}, ignore_index=True)
Execute the following line to remove the comma and dollar sign from the Revenue column.
tesla_revenue["Revenue"] = tesla_revenue["Revenue"].replace({'\$': '', ',': ''}, regex=True)
Execute the following lines to remove an null or empty strings in the Revenue column.
# Convert non-numeric values to NaN and drop rows with NaN values in Revenue
tesla_revenue["Revenue"] = pd.to_numeric(tesla_revenue["Revenue"], errors='coerce')
tesla_revenue.dropna(subset=["Revenue"], inplace=True)
# Convert Date column to datetime
tesla_revenue["Date"] = pd.to_datetime(tesla_revenue["Date"])
Display the last 5 row of the tesla_revenue dataframe using the tail function. Take a screenshot of the results.
tesla_revenue.tail()
| Date | Revenue | |
|---|---|---|
| 48 | 2010-09-30 | 31 |
| 49 | 2010-06-30 | 28 |
| 50 | 2010-03-31 | 21 |
| 51 | 2009-09-30 | 46 |
| 52 | 2009-06-30 | 27 |
Using the Ticker function enter the ticker symbol of the stock we want to extract data on to create a ticker object. The stock is GameStop and its ticker symbol is GME.
gme = yf.Ticker("GME")
Using the ticker object and the function history extract stock information and save it in a dataframe named gme_data. Set the period parameter to "max" so we get information for the maximum amount of time.
gme_data= gme.history(period="max")
Reset the index using the reset_index(inplace=True) function on the gme_data DataFrame and display the first five rows of the gme_data dataframe using the head function. Take a screenshot of the results and code from the beginning of Question 3 to the results below.
gme_data.reset_index(inplace=True)
gme_data.head()
| Date | Open | High | Low | Close | Volume | Dividends | Stock Splits | |
|---|---|---|---|---|---|---|---|---|
| 0 | 2002-02-13 00:00:00-05:00 | 1.620128 | 1.693350 | 1.603296 | 1.691666 | 76216000 | 0.0 | 0.0 |
| 1 | 2002-02-14 00:00:00-05:00 | 1.712707 | 1.716074 | 1.670626 | 1.683250 | 11021600 | 0.0 | 0.0 |
| 2 | 2002-02-15 00:00:00-05:00 | 1.683251 | 1.687459 | 1.658002 | 1.674834 | 8389600 | 0.0 | 0.0 |
| 3 | 2002-02-19 00:00:00-05:00 | 1.666418 | 1.666418 | 1.578047 | 1.607504 | 7410400 | 0.0 | 0.0 |
| 4 | 2002-02-20 00:00:00-05:00 | 1.615920 | 1.662210 | 1.603296 | 1.662210 | 6892800 | 0.0 | 0.0 |
Use the requests library to download the webpage https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0220EN-SkillsNetwork/labs/project/stock.html. Save the text of the response as a variable named html_data_2.
url = "https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0220EN-SkillsNetwork/labs/project/stock.html"
html_data2=requests.get(url).text
Parse the html data using beautiful_soup using parser i.e html5lib or html.parser.
beautiful_soup=BeautifulSoup(html_data2,'html.parser')
Using BeautifulSoup or the read_html function extract the table with GameStop Revenue and store it into a dataframe named gme_revenue. The dataframe should have columns Date and Revenue. Make sure the comma and dollar sign is removed from the Revenue column.
# Step 1-2: Create an empty DataFrame
gme_revenue = pd.DataFrame(columns=["Date", "Revenue"])
# Step 3: Locate the relevant table
# Find all tbody elements and select the second one where the Tesla revenue table is located
table = beautiful_soup.find_all("tbody")[1]
# Step 4: Iterate through rows in the table body
for row in table.find_all("tr"):
columns = row.find_all("td")
# Check if there are two columns (Date and Revenue) in each row
if len(columns) == 2:
date = columns[0].text.strip() # Extract and clean the Date text
revenue = columns[1].text.strip() # Extract and clean the Revenue text
#Step 5: Extract Data from Columns
if revenue:
gme_revenue = gme_revenue.append({"Date": date, "Revenue": revenue}, ignore_index=True)
gme_revenue["Revenue"] = gme_revenue["Revenue"].replace({'\$': '', ',': ''}, regex=True)
# Convert non-numeric values to NaN and drop rows with NaN values in Revenue
gme_revenue["Revenue"] = pd.to_numeric(gme_revenue["Revenue"], errors='coerce')
gme_revenue.dropna(subset=["Revenue"], inplace=True)
# Convert Date column to datetime
gme_revenue["Date"] = pd.to_datetime(gme_revenue["Date"])
gme_revenue.tail()
| Date | Revenue | |
|---|---|---|
| 57 | 2006-01-31 | 1667 |
| 58 | 2005-10-31 | 534 |
| 59 | 2005-07-31 | 416 |
| 60 | 2005-04-30 | 475 |
| 61 | 2005-01-31 | 709 |
def make_graph(stock_data, revenue_data, stock):
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, subplot_titles=("Historical Share Price", "Historical Revenue"), vertical_spacing = .3)
stock_data_specific = stock_data[stock_data.Date <= '2021--06-14']
revenue_data_specific = revenue_data[revenue_data.Date <= '2021-04-30']
fig.add_trace(go.Scatter(x=pd.to_datetime(stock_data_specific.Date, infer_datetime_format=True), y=stock_data_specific.Close.astype("float"), name="Share Price"), row=1, col=1)
fig.add_trace(go.Scatter(x=pd.to_datetime(revenue_data_specific.Date, infer_datetime_format=True), y=revenue_data_specific.Revenue.astype("float"), name="Revenue"), row=2, col=1)
fig.update_xaxes(title_text="Date", row=1, col=1)
fig.update_xaxes(title_text="Date", row=2, col=1)
fig.update_yaxes(title_text="Price ($US)", row=1, col=1)
fig.update_yaxes(title_text="Revenue ($US Millions)", row=2, col=1)
fig.update_layout(showlegend=False,
height=900,
title=stock,
xaxis_rangeslider_visible=True)
fig.show()
Use the make_graph function to graph the Tesla Stock Data, also provide a title for the graph. Note the graph will only show data upto June 2021
make_graph(tesla_data, tesla_revenue, 'Tesla')
Use the make_graph function to graph the GameStop Stock Data, also provide a title for the graph. The structure to call the make_graph function is make_graph(gme_data, gme_revenue, 'GameStop'). Note the graph will only show data upto June 2021.
make_graph(gme_data, gme_revenue, 'GameStop')